package com.menggudf.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.alibaba.fastjson.JSON;
import com.menggudf.entity.Invitation;
import com.menggudf.model.*;
import com.menggudf.model.response.UserInfoResponse;
import com.menggudf.service.InvitationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.menggudf.service.BlackListService;
import com.menggudf.service.UserService;

/**
 * 手机端用户controller
 * @author Administrator
 *
 */
@Slf4j
@Controller
@RequestMapping("/user")
public class UserController {
	
	@Autowired
	UserService userService;
	
	@Autowired
	BlackListService blackListService;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    InvitationService invitationService;
	
    /*private final String[] arr2={"13510281855","15999948493","13923758878","18620303678","13798555870","13922816885","15818563863","18018701293","13502884011"};*/
    
    @RequestMapping("/login")
    @ResponseBody
    public ResultModel login(HttpServletRequest request,
            HttpServletResponse response,
            @RequestParam("phone") String phone,
            @RequestParam("psw") String passWord,  
            HttpSession httpSession){
        /*boolean flag = false;
        List<BlackListModel> mlist = blackListService.getListByType(1);
        for(BlackListModel s : mlist){
            if(s.getNum().equalsIgnoreCase(phone)){
                flag = true;
            }
        }
        
        if(!flag){
            return ResultModel.fail("拒绝登录",null);
        }*/
        ResultModel model =userService.userLogin(phone, passWord);
        if(model.getResultCode()==ResultStatus.RESULT_STATUS_SUCCESS.getValue()){
            UserModel userModel = (UserModel) model.getContent();
            httpSession.setAttribute("userModel", userModel);
        }
        @SuppressWarnings("unused")
        UserModel m=(UserModel) httpSession.getAttribute("userModel");
        log.info("用户的sessionid是：{},session内容是：{}", httpSession.getId(),JSON.toJSONString(m));
        redisTemplate.opsForValue().set(httpSession.getId(),m,7200, TimeUnit.SECONDS);
        return model;
    }
    
    @RequestMapping("/currRole")
    @ResponseBody
    public ResultModel currRole(
            @RequestParam("currRole") String currRole,
            @RequestParam("isMainRole") Integer isMainRole){
        return userService.currRole(currRole,isMainRole);
    }
    
    @RequestMapping("/getRoles")
    @ResponseBody
    public ResultModel  getRoles(
            HttpServletRequest request,
            HttpServletResponse response,
            HttpSession httpSession,
            @RequestParam("primaryRole") String primaryRole){
        UserModel m = (UserModel) httpSession.getAttribute("userModel");
        if(m==null){
            return ResultModel.fail("超时，请重新登录", null);
        }
        if(!primaryRole.equalsIgnoreCase(m.getUserCode())){
            return ResultModel.fail("当前用户变更，请重新登录！", null);
        }
        return userService.getRoles(primaryRole);
    }
    
    
    
    
    
	
	/**
	 * 退出登录
	 * @param request
	 * @param response
	 * @param httpSession
	 * @return
	 */
	@RequestMapping("/loginOut")
	@ResponseBody
	public ResultModel loginOut(HttpServletRequest request,
			HttpServletResponse response,HttpSession httpSession){
		if(httpSession.getAttribute("userModel")!=null){
			httpSession.removeAttribute("userModel");
		}
		if(httpSession.getAttribute("userModel")==null){
			 return ResultModel.success();
		}else{
			 return ResultModel.fail();
		}
	}
	
	   /**
     * 获取用户列表
     * @return
     */
    @RequestMapping("/getUserList")
    @ResponseBody
    public Map<String, Object> getUserList(
            @RequestParam(value="userCode",required=false) String userCode,
            @RequestParam(value="userName",required=false) String userName,
            @RequestParam("limit") int pageSize,
            @RequestParam("offset") int offset,
            @RequestParam("startTime") Date startTime,
            @RequestParam("endTime") Date endTime){
                return userService.getUserList(userCode,userName,pageSize,offset,startTime,endTime);
        
    }
    
    @RequestMapping("/checkSmsCode")
    @ResponseBody
    public ResultModel checkSmsCode(
            @RequestParam(value="sms") String sms,
            HttpServletRequest request,
            HttpServletResponse response,
            HttpSession httpSession){
        UserModel uModel = (UserModel) httpSession.getAttribute("userModel");
        if(!uModel.getSms().equalsIgnoreCase(sms)){
            return ResultModel.fail("验证码不正确", null);
        }else{
            return ResultModel.success("验证通过", null);
        }
        
    }
    
    @RequestMapping("/register")
    @ResponseBody
    public ResultModel register(
            @RequestParam(value="phone") String phone,
            @RequestParam(value="invitationCode") String invitationCode,
            @RequestParam(value="password") String password,
            @RequestParam(value="sex") Integer sex,
            @RequestParam(value="birthday") String birthday,
            @RequestParam(value="isRead") Integer isRead) {
        try {
            SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd");
            if(birthday==null||birthday==""){
                birthday=sdf.format(new Date());
            }
            Date birth = sdf.parse(birthday);
            UserModel userModel = new UserModel();
            userModel.setUserName(phone);
            userModel.setBirth(birth);
            userModel.setPhone(phone);
            userModel.setPassword(password);
            userModel.setSex(sex);
            userModel.setIsRead(isRead);
            return userService.userRegister(userModel,invitationCode);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return ResultModel.fail("注册失败，请重新输入", null);

    }
    
    @RequestMapping("/editUser")
    @ResponseBody
    public ResultModel editUser(
            @RequestParam("currRole") String currRole,
            @RequestParam("isMainRole") Integer isMainRole,
            @RequestParam("name") String name,
            @RequestParam("sex") Integer sex,
            @RequestParam("birth") String birthday) throws ParseException{
        SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd");
        if(birthday==null||birthday==""){
            birthday=sdf.format(new Date());
        }
        Date birth = sdf.parse(birthday);
        return userService.editUser(currRole,isMainRole,name,sex,birth);
    }
    
    @RequestMapping("/findUserPsw")
    @ResponseBody
    public ResultModel findUserPsw(
            @RequestParam("phone") String phone,
            @RequestParam("password") String password,
            @RequestParam("passNum") String passNum,
            HttpServletRequest request,
            HttpServletResponse response,
            HttpSession httpSession){
        UserModel m=(UserModel) httpSession.getAttribute("userModel");
        if(!m.getSms().equalsIgnoreCase(passNum)){
            return ResultModel.fail("验证码不正确", null);
        }
        return userService.findUserPsw(phone,password);
    }
    
    @RequestMapping("/createRole")
    @ResponseBody
    public ResultModel createRole(
            @RequestParam("name") String name,
            @RequestParam("sex") Integer sex,
            @RequestParam("birth") String birthday,
            @RequestParam("userCode") String userCode) throws ParseException{
        SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd");
        if(birthday==null||birthday==""){
            birthday=sdf.format(new Date());
        }
        Date birth = sdf.parse(birthday);
        return userService.createRole(name,sex,birth,userCode);
    }
    
    //添加BMI数据
    @RequestMapping("/addBMIRecord")
    @ResponseBody
    public ResultModel addBMIRecord(
            @RequestParam(value="userCode") String userCode,
            @RequestParam(value="roleCode",required=false) String roleCode,
            @RequestParam("bodyWeight") Double bodyWeight,
            @RequestParam("height") Double height){
        return userService.addBMIRecord(userCode,roleCode,bodyWeight,height);
    }
    
    //获取BMI数据
    @RequestMapping("/getBMIRecord")
    @ResponseBody
    public ResultModel getBMIRecord(
            @RequestParam(value="userCode") String userCode,
            @RequestParam(value="roleCode",required=false) String roleCode){
        return userService.getBMIRecord(userCode,roleCode);
    }

    @RequestMapping("/getUserInfo")
    @ResponseBody
    public ResultModel getUserInfo(HttpSession httpSession) {
        UserInfoResponse userInfoResponse = new UserInfoResponse();
        UserModel m = (UserModel) httpSession.getAttribute("userModel");

        return null;
    }
    
}
